package listbyorder.access001_100.test23;

import listbyorder.utils.ListNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/29 14:43
 */
public class Solution1 {

    // 归并
    public ListNode mergeKLists(ListNode[] lists) {
        // 归并排序
        if (lists == null || lists.length == 0) return null;
        if (lists.length == 1) return lists[0];
        return getAns(lists, 0, lists.length - 1);
    }

    private ListNode getAns(ListNode[] lists, int l, int r) {
        if (l > r) return null;
        if (l == r) {
            return lists[l];
        }
        int mid = (l + r) >> 1;
        ListNode left = getAns(lists, l, mid);
        ListNode right = getAns(lists, mid + 1, r);
        return merger(left, right);
    }

    private ListNode merger(ListNode left, ListNode right) {
        if (left == null) return right;
        if (right == null) return left;
        if (left.val < right.val) {
            left.next = merger(left.next, right);
            return left;
        } else {
            right.next = merger(left, right.next);
            return right;
        }
    }
}
